package com.taobao.home.api;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.taobao.base.model.*;
import com.taobao.base.utils.SecurityUtil;
import com.taobao.home.feignclient.AuthServiceClient;
import com.taobao.home.model.dto.StoreDto;
import com.taobao.home.model.dto.StorePreviewDto;
import com.taobao.home.service.StoreService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("store")
@CrossOrigin(origins = "*")
public class StoreController {

    @Autowired
    ObjectMapper objectMapper;
    @Autowired
    private StoreService storeService;
    @Autowired
    private AuthServiceClient authServiceClient;

    @GetMapping("/storeAll")
    public RestResponse<List<StoreDto>> getAllStore() {

        //取出当前用户身份
        SecurityUtil.TbUser user = SecurityUtil.getUser();
        System.err.println(user);
        return storeService.getAllStore();
    }

    /**
     * 关注页店铺预览
     */
    @PostMapping("/getStorePreview")
    public PageResult<StorePreviewDto> getStorePreview(PageParams pageParams) {

        System.out.println(pageParams);

        return storeService.getStorePreview(pageParams);
    }

    /**
     * 根据店铺id获取店铺信息
     */
    @GetMapping("/getStoreById/{storeId}")
    public RestResponse<StoreDto> getStoreById(@PathVariable("storeId") Integer storeId) {
        System.out.println(storeId);
        return storeService.getStoreById(storeId);
    }

    /**
     * 添加店铺
     */
    @PostMapping("/addStore")
    public RestResponse addStore(@RequestBody StoreDto storeDto, HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);
        System.out.println(storeDto);

        return storeService.addStore(storeDto, tokenUser.getUserId());
    }

    /**
     * 根据店铺id获取我的店铺
     */
    @GetMapping("/getMyStore")
    public RestResponse<List<StoreDto>> getMyStore(HttpServletRequest request) {
        TokenUser tokenUser = getTokenUser(request);

        RestResponse<List<StoreDto>> myStoreList = storeService.getMyStore(tokenUser.getUserId());

        return myStoreList;
    }

    /**
     * 根据店铺id 删除店铺
     */
    @DeleteMapping("/deleteStore/{storeId}")
    public RestResponse<String> deleteStore(@PathVariable("storeId") Integer storeId) {

        RestResponse<String> stringRestResponse = storeService.deleteStore(storeId);

        return stringRestResponse;
    }

    /**
     * 解析token 获取用户信息
     */
    private TokenUser getTokenUser(HttpServletRequest request) {
        // 从请求头中获取 Authorization 字段
        TokenUser tokenUser = null;
        String authorizationHeader = request.getHeader("Authorization");
        // 检查是否包含 Bearer Token
        if (authorizationHeader != null && authorizationHeader.startsWith("Bearer ")) {
            String token = authorizationHeader.substring(7); // 去掉 "Bearer " 前缀
            TokenResponse tokenResponse = authServiceClient.checkToken(token);
            String jsonString = tokenResponse.getUser_name();
            // 转TokeUser对象
            try {
                tokenUser = objectMapper.readValue(jsonString, TokenUser.class);
                System.out.println(tokenUser);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
        }
        return tokenUser;
    }

}
